<template>
  <div class="smartcoupon-create Row_content" style="width:890px;">
    <Form v-show="!filterShow" inline
      ref="formValidate"
      :model="formValidate"
      :rules="ruleValidate"
      :label-width="130">
      <FormItem label="活动名称:" prop="activityName">
        <Input v-model="formValidate.activityName" placeholder="请输入" class='input-wid' :maxlength="20" @on-keyup="filterActivityName" @on-blur="filterActivityName"></Input>
      </FormItem>
      <FormItem label="会员筛选:" prop="memberNum">
        <Input search @on-focus="showFilter" v-model="formValidate.memberNum" />
      </FormItem>
      <FormItem label="优惠券列表:" style="width: 830px" prop="coupons">
        <select-coupon v-model="formValidate.coupons" @addcoupon="Dmodal = true"></select-coupon>
      </FormItem>
      <FormItem label="发放时间:"
                prop="activityStart">
        <DatePicker :value="formValidate.activityStart"
                    type="datetime"
                    :editable="false"
                    placeholder="请选择"
                    @on-change="activityStartChange"
                    style="width: 280px"></DatePicker>
      </FormItem>
      <FormItem></FormItem>
      <FormItem label="微信消息模板:" prop="sendWechat">
        <Select v-model="formValidate.sendWechat" @on-change="selectWechatChange">
          <Option v-for="(item, index) in sendWechats"
                  :value="item.id"
                  :key="index">
            {{ item.templateName }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="短信消息模板:" prop="sendMessage">
        <Select v-model="formValidate.sendMessage" @on-change="selectMessageChange">
          <Option v-for="(item, index) in sendMessages"
                  :value="item.id"
                  :key="index">
            {{ item.templateName }}
          </Option>
        </Select>
      </FormItem>
      <FormItem label="微信消息模板:" style="width: 830px" v-show="formValidate.sendWechat !== '-1'">
        <Input
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          style="width:700px" disabled v-model="wechat"></Input>
      </FormItem>
      <FormItem label="短信消息模板:" style="width: 830px" v-show="formValidate.sendMessage !== '-1'">
        <Input
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          style="width:700px" disabled v-model="message"></Input>
      </FormItem>
      <FormItem label="备注:" prop="remark">
        <Input v-model="formValidate.remark" placeholder="请输入" type="textarea" :autosize="{minRows: 4,maxRows: 8}" :maxlength="100"></Input>
        <span class="rol_tipsd">
          {{ formValidate.remark.length }}/100
        </span>
      </FormItem>
      <FormItem></FormItem>
      <FormItem class="form-btn"
                style="margin-top: 5px;">
        <Button type="primary"
                class="system-submit-btn"
                @click="handleSubmit"
                >确定</Button>
        <Button class="system-submit-btn"
                @click="handleReset"
                style="margin-left: 8px">取消</Button>
      </FormItem>
    </Form>
    <drawer-coupon v-model="Dmodal" :data="formValidate.coupons" :origin="2" @sure="handleSelectCoupon" :maxsize="20"></drawer-coupon>
    <filter-member v-show="filterShow" @on-cancel="filterCancel" @on-sure="filterSure"></filter-member>
  </div>
</template>

<script>
import { routeEqual } from '@/libs/util'
import { mapState } from 'vuex'
import DrawerCoupon from '@/view/components/drawer-coupon/index.vue'
import SelectCoupon from '@/view/components/select-coupon/index.vue'
import FilterMember from '@/view/components/filter-member/index.vue'
import { saveCoupon } from '@/api/market/smartcoupon'
import { getMessages } from '@/api/market/message'
export default {
  name: 'market_smart_coupon_create',
  components: { SelectCoupon, DrawerCoupon, FilterMember },
  data () {
    return {
      Dmodal: false,
      filterShow: false,
      formValidate: {
        activityName: '',
        memberNum: '',
        activityStart: '',
        sendWechat: '-1',
        sendMessage: '-1',
        remark: '',
        coupons: []
      },
      queryMemberDTO: {},
      ruleValidate: {
        activityName: { required: true, message: '请填写活动名称', trigger: 'blur' },
        memberNum: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!this.formValidate.memberNum) {
              callback(new Error('请筛选会员'))
            } else if (this.formValidate.memberNum <= 0) {
              callback(new Error('会员数量需大于0'))
            } else {
              callback()
            }
          }
        },
        coupons: { required: true, message: '请添加优惠券' },
        sendWechat: { required: true, message: '请选择是否发送微信消息' },
        sendMessage: { required: true, message: '请选择是否发送短信消息' },
        activityStart: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            const activityStart = new Date(this.formValidate.activityStart).getTime()
            if (!activityStart) {
              callback(new Error('请选择发放时间'))
            } else if (activityStart < new Date().getTime()) {
              callback(new Error('发放时间必须晚与当前时间'))
            } else {
              callback()
            }
          }
        }
      },
      sendWechats: [{ templateName: '无', id: '-1' }],
      sendMessages: [{ templateName: '无', id: '-1' }],
      wechat: '',
      message: ''
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId
    })
  },
  mounted () {
    this.getEnums(1).then(data => {
      this.sendWechats = [{ templateName: '无', id: '-1' }].concat(data || [])
    })
    this.getEnums(2).then(data => {
      this.sendMessages = [{ templateName: '无', id: '-1' }].concat(data || [])
    })
  },
  methods: {
    selectWechatChange (value) {
      this.formValidate.sendWechat = value
      if (value) {
        this.sendWechats.forEach(item => {
          if (item.id === value) {
            this.wechat = item.content
          }
        })
      } else {
        this.wechat = ''
      }
    },
    selectMessageChange (value) {
      this.formValidate.sendMessage = value
      if (value) {
        this.sendMessages.forEach(item => {
          if (item.id === value) {
            this.message = item.content
          }
        })
      } else {
        this.message = ''
      }
    },
    getEnums (templateType) {
      return new Promise((resolve, reject) => {
        getMessages({
          templateType,
          merchantId: this.merchantId,
          suitableType: 9,
          status: 1
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            resolve(result.data)
          } else {
            this.$Message.error(`${result.error}`)
          }
        }).catch(err => {
          this.$Message.error(`${err}`)
        })
      })
    },
    showFilter () {
      this.filterShow = true
    },
    filterCancel () {
      this.filterShow = false
    },
    filterSure (count, queryMemberDTO) {
      this.filterShow = false
      this.formValidate.memberNum = count + ''
      this.queryMemberDTO = queryMemberDTO
    },
    activityStartChange (time) {
      this.formValidate.activityStart = time
    },
    handleSelectCoupon (val) {
      this.formValidate.coupons = val
    },
    handleSubmit () {
      this.$refs.formValidate.validate(val => {
        if (val) {
          const formValidate = this.formValidate
          let templates = []
          formValidate.sendMessage !== '-1' && templates.push({ templateId: formValidate.sendMessage })
          formValidate.sendWechat !== '-1' && templates.push({ templateId: formValidate.sendWechat })
          const params = {
            merchantId: this.merchantId,
            activityName: formValidate.activityName,
            memberNum: formValidate.memberNum,
            activityStart: formValidate.activityStart,
            remark: formValidate.remark,
            giftSaveDTOs: formValidate.coupons,
            queryMemberDTO: this.queryMemberDTO,
            templates
          }
          saveCoupon(params).then(res => {
            const result = res.data || {}
            if (result.status === 200) {
              this.$Message.success('新增成功！')
              this.handleReset()
            } else {
              this.$Message.error(`${result.error}`)
            }
          })
        }
      })
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'market_smart_coupon_list'
        })
      })
    },
    filterActivityName () {
      this.formValidate.activityName = this.formValidate.activityName.replace(/[^a-zA-Z0-9\u4E00-\u9FA5]/g, '')
    }
  }
}
</script>

<style lang='less'>
  .smartcoupon-create {
    .input-wid{
      width: 280px;
    }
  }
  .ivu-spin-fix {
    background-color: rgba(255, 255, 255, 0)
  }
</style>
